/*
* ejs 模板引擎的使用
* 1. npm install koa-views --save
*
* 2. npm install ejs --save
*
* 3. app.use(views(__dirname, {extension:'ejs'}))
*
* 4. await ctx.render('index')
*
* */

const Koa = require('koa')
const Router = require('koa-router')
const views = require('koa-views')

const app = new Koa()
const router = new Router()


//配置模板引擎中间件 第三方中间件
//app.use(views('views', {map: {html: 'ejs'}}))  //这种方法需要用html后缀名
app.use(views('views', {extension: 'ejs'}))

//写一个中间件配置公共数据
app.use(async (ctx, next) => {
  ctx.state.username = 'zhangsan'
  await next()
})

router.get('/', async (ctx) => {
  await ctx.render('index', {
    username: ctx.state.username
  })
})

app.use(router.routes())
app.use(router.allowedMethods())

app.listen(3000, () => {
  console.log('服务启动成功')
})